package com.smile.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.smile.interf.ServerViewInterface;
import com.smile.model.ChatSocket;

public class ServerListener extends Thread {

	private int port;
	private boolean isClose = false;
	private ServerViewInterface serverViewInterface;
	private ServerSocket serverSocket = null;

	public ServerListener(String port, ServerViewInterface serverViewInterface) {
		this.port = Integer.parseInt(port);
		this.serverViewInterface = serverViewInterface;
		ChatManager.getCM().setServerViewInterface(serverViewInterface);
	}

	public void closeSocket() {
		isClose = true;
		try {
			// socket.close();
			ChatManager.getCM().delAll();
			serverSocket.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		serverViewInterface.setMessage("服务器端口" + port + "已关闭...\n", 0);
	}

	@Override
	public void run() {

		try {
			serverSocket = new ServerSocket(port);
			serverViewInterface.setMessage("服务器端口" + port + "已开启...\n", 0);
			int number = 0;
			while (!isClose) {
				Socket socket = serverSocket.accept();
				ChatSocket cs = new ChatSocket(number + "", socket);
				cs.start();
				cs.csTouch();
				ChatManager.getCM().add(cs);
				number++;
			}

		} catch (IOException e) {
			String error = e.getMessage();
//			System.out.println(error);
			switch (error) {
			case "socket closed":
				break;
			case "Address already in use: JVM_Bind":
				serverViewInterface.setMessage("服务器端口" + port + "开启失败...端口被占用\n", 0);
				break;

			default:
				serverViewInterface.setMessage("服务器端口" + port + "开启失败...\n", 0);
				break;
			}
		} catch (IllegalArgumentException e) {
			serverViewInterface.setMessage("服务器端口" + port + "开启失败...端口号在1-65535之间\n", 0);
		}

	}

}
